package com.rimi.controller;

import com.alipay.easysdk.factory.Factory;
import com.rimi.commons.CommonResult;
import com.rimi.model.dto.RefundDTO;
import com.rimi.model.dto.ShippingAddressDto;
import com.rimi.model.vo.PaymentVo;
import com.rimi.model.vo.RefundVo;
import com.rimi.service.AlipayService;
import com.rimi.service.OrderService;
import com.rimi.service.UserService;
import com.rimi.util.UserIdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@Slf4j
@Api(description = "支付宝支付接口",tags = "支付功能")
@CrossOrigin
public class AlipayController {

   @Autowired
   AlipayService alipayService;

   @Autowired
   OrderService orderService;

   @Autowired
   UserService userService;

    /**
     *  网页支付
     * @param orderId 订单Id
     * @return 支付页
     */
   @PostMapping("/user/page{orderId}")
   @ApiOperation("将显示的订单中的订单id传过来，会自动打开支付宝的支付页面 page为电脑网页支付")
   public String pagePay(@PathVariable Integer orderId){
       //orderId = 12;
       PaymentVo paymentVo = orderService.findOrderByOrderId(orderId,UserIdUtil.getUserId());
       return alipayService.pagePay(paymentVo);
   }

    /**
     *  手机网页支付
     * @param  orderId 订单Id
     * @return 支付网页
     */
    @PostMapping("/user/wap{orderId}")
    @ApiOperation("将显示的订单中的订单id传过来，会自动打开支付宝的支付页面，wap为手机网页支付，可不做")
    public String wapPay(@PathVariable Integer orderId){
        //orderId = 3;
        PaymentVo paymentVo = orderService.findOrderByOrderId(orderId,UserIdUtil.getUserId());
        return alipayService.wapPay(paymentVo);
    }

    /**
     * 支付宝回调函数
     * @param request
     * @return 支付宝返回支付消息
     * @throws Exception
     */
   @PostMapping("/user/notify")
   @ApiOperation("支付成功后的支付宝回调函数，不用实现此接口")
   public String notify(HttpServletRequest request) throws Exception {
       if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
           System.out.println("=========支付宝异步回调========");
           Map<String, String> params = new HashMap<>();
           Map<String, String[]> requestParams = request.getParameterMap();
           for (String name : requestParams.keySet()) {
               params.put(name, request.getParameter(name));
           }
           // 支付宝验签
           if (Factory.Payment.Common().verifyNotify(params)) {
               // 验签通过
               System.out.println("交易名称: " + params.get("subject"));
               System.out.println("交易状态: " + params.get("trade_status"));
               System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
               System.out.println("商户订单号: " + params.get("out_trade_no"));
               System.out.println("交易金额: " + params.get("total_amount"));
               System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
               System.out.println("买家付款时间: " + params.get("gmt_payment"));
               System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
               //交易名称
               String subject = params.get("subject");

               //支付宝交易凭证号
               String tradeNo = params.get("trade_no");

               //商户订单号(我们自动生成的订单号)
               String orderNum = params.get("out_trade_no");

               //买家付款时间
               String gmt_payment = params.get("gmt_payment");
               //创建SimpleDateFormat对象实例并定义好转换格式
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               Date paymentTime = sdf.parse(gmt_payment);

               //买家付款金额
               String buyer_pay_amount = params.get("buyer_pay_amount");
               Double paymentPrice = Double.parseDouble(buyer_pay_amount);
               //获取默认地址
               String defaultAddressInfo = userService.findDefaultAddressInfo(UserIdUtil.getUserId());
               //修改数据库
               orderService.paid(orderNum,tradeNo,paymentTime,paymentPrice,defaultAddressInfo);
           }
       }
       return "success";
   }

    /**
     * 退款页面 通过orderId查询订单号 和 金额 进行退款
     * @param  orderId
     * @return
     */
    @PostMapping("/user/refund{orderId}")
    @ApiOperation("退款方法，根据订单id查询到该笔订单，并把订单退款原因，退款类型，退款图片，退款金额传过来进行退款")
    public String refund(@PathVariable Integer orderId,@RequestBody RefundDTO refundDTO) {
        RefundVo refundVo = orderService.findOrderRefundByOrderId(orderId,UserIdUtil.getUserId());
        //前端传过来的退款原因
        refundVo.setRefundType(refundDTO.getRefundType());
        refundVo.setRefundReason(refundDTO.getRefundReason());
        refundVo.setRefundImg(refundDTO.getRefundImg());
        refundVo.setRefundPrice(refundDTO.getRefundPrice());
        //退款方法
        return alipayService.refund(refundVo);
    }
}
